import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, orderStatus, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Table,
    Button,
    Card,
    Col,
    Input,
    Row,
    Select,
    DatePicker,
    Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import Pagination from '../../components/Pagination';

const { Item } = Form;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    logisCenterPayexpList: any;
    match: { params: { bid: number } };
    INITINFO: any;
    location: any;
    loading: boolean;
    screen: string;
}

interface TableListState {
    current: number;
    pageSize: number | undefined;
    formValues: any;
    rowId: number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
    logisCenterPayexpList,
    common: { INITINFO },
    global: { screen },
    loading,
}: any) => ({
    logisCenterPayexpList,
    INITINFO,
    screen,
    loading: loading.effects['logisCenterPayexpList/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
    columns: any = [
        {
            title: '运单号',
            dataIndex: 'expCode',
            width: 150,
            render: (text: any, record: any) => (
                <Tooltip title={text}>
                    <div
                        className="wordOmit nameLink"
                        onClick={() => this.handleShowDetail(record.id, text)}
                    >
                        {text}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '快递公司',
            dataIndex: 'expressName',
            width: 100,
        },
        {
            title: '收件人',
            dataIndex: 'consigneePhone',
            width: 120,
        },
        {
            title: '物流中心',
            dataIndex: 'logisName',
            width: 150,
            render: (text: any) => (
                <Tooltip title={text}>
                    <div title={text} className="wordOmit">
                        {text || '--'}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '接驳时间',
            dataIndex: 'createTime',
            width: 150,
        },
        {
            title: '到付金额(元)',
            dataIndex: 'payment',
            width: 100,
            render: (text: number) => text / 100,
        },
        {
            title: '付款状态',
            dataIndex: 'isPaidName',
            width: 80,
        },
        {
            title: '付款方式',
            dataIndex: 'chargeWayName',
            width: 80,
        },
        {
            title: '取件时间',
            dataIndex: 'outTime',
            width: 150,
            render: (text: string) => text || '--',
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            width: 80,
            render: (text: string) => orderStatus[text],
        },
        {
            title: '操作',
            fixed: 'right',
            dataIndex: 'id',
            width: 60,
            render: (id: any, record: any) => (
                <span
                    className="operLink"
                    onClick={() => this.handleShowDetail(id, record.expCode)}
                >
                    详情
                </span>
            ),
        },
    ];

    state: TableListState = {
        current: 1,
        pageSize: 20,
        formValues: {},
        rowId: 0,
    };

    static getDerivedStateFromProps(props: any, state: any) {
        const { search } = props.location;
        const query = qs.parse(search, { ignoreQueryPrefix: true });
        const { page, psize, ...formValues } = query;

        return {
            ...state,
            formValues,
            current: Number(page) || 1,
            pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
        };
    }

    componentDidMount() {
        this.setFieldsValue();
        this.fetchLogisList();
        this.fetchExpressList();
        this.fetchPayexpList();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { formValues, current, pageSize } = this.state;
        if (!_.isEqual(formValues, prevState.formValues)
            || current !== prevState.current
            || pageSize !== prevState.pageSize
        ) {
            this.setFieldsValue();
            this.fetchPayexpList();
        }
    }

    // 设置表单值
    setFieldsValue = () => {
        const {
            formValues: {
                startTime, endTime, maxId, minId, ...others
            },
        } = this.state;

        if (startTime) {
            others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
        } else {
            others.start_end_time = [
                moment(
                    moment()
                        .subtract(3, 'days')
                        .format('YYYY-MM-DD 00:00:00'),
                ),
                '',
            ];
        }

        if (startTime === '') others.start_end_time = ['', ''];
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(others);
    };

    // 获取物流中心列表
    fetchLogisList = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'common/fetchLogisList' });
    };

    // 获取校园小区列表
    fetchExpressList = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'common/fetchExpressList' });
    };

    // 获取列表数据
    fetchPayexpList = () => {
        const {
            location: { query },
            logisCenterPayexpList: { data },
        } = this.props;

        const { maxId, minId, ...other } = query;
        const search = qs.stringify(other);
        const { current } = this.state;
        const contentObj = data.content.find((item: any) => item.current === current);

        if (contentObj && search === contentObj.search) {
            this.setState({});
        } else {
            const { dispatch } = this.props;
            dispatch({
                type: 'logisCenterPayexpList/fetch',
                payload: {
                    params: this.getQueryParams(),
                    search,
                    maxId,
                    minId,
                },
            });
        }
    };

    // 获取查询参数
    getQueryParams = () => {
        const { formValues, current: pageIndex, pageSize } = this.state;
        const params = { ...formValues, pageIndex, pageSize };

        if (params.startTime === undefined) {
            params.startTime = moment()
                .subtract(3, 'days')
                .format('YYYY-MM-DD 00:00:00');
        }

        return params;
    };

    /**
     * 查询
     */
    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();

        const { form: { validateFields } } = this.props;
        validateFields((err, fieldsValue) => {
            if (err) return;

            if (fieldsValue.start_end_time) {
                if (fieldsValue.start_end_time[0]) {
                    fieldsValue.startTime = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    fieldsValue.startTime = '';
                }

                if (fieldsValue.start_end_time[1]) {
                    fieldsValue.endTime = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    fieldsValue.endTime = '';
                }
            } else {
                fieldsValue.startTime = '';
                fieldsValue.endTime = '';
            }
            delete fieldsValue.start_end_time;

            const query = { page: 1, ...fieldsValue };
            const { dispatch } = this.props;
            addTab(dispatch, {
                name: '到付件管理',
                url: `${pathname}?${qs.stringify(query)}`,
                isTopMenu: true,
            });
            dispatch({ type: 'logisCenterPayexpList/cleanCount' });
        });
    };

    /**
     * 重置
     */
    handleReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '到付件管理',
            url: pathname,
            isTopMenu: true,
        });
        dispatch({ type: 'logisCenterPayexpList/cleanCount' });
    };

    /**
     * 导出
     */
    handleExport = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterPayexpList/export',
            payload: this.getQueryParams(),
        });
    };

    /**
     * 查看总数
     */
    handleShowCount = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterPayexpList/count',
            payload: this.getQueryParams(),
        });
    };

    /**
     * 查看详情
     */
    handleShowDetail = (id: number, expCode: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `查看${expCode}`,
            url: `${pathname}/detail/${id}`,
        });
    };

    // 分页
    onSelectChange = (type: string) => {
        const { formValues, current, pageSize: psize } = this.state;
        const { logisCenterPayexpList: { data } } = this.props;

        const query = {
            ...formValues,
            page: type === 'prev' ? current - 1 : current + 1,
            psize,
        };

        const contentObj = data.content.find((item: any) => item.current === current);
        if (type === 'prev') {
            if (contentObj?.list?.length) {
                query.minId = contentObj.list[0].id;
            } else {
                query.minId = contentObj.maxId || contentObj.minId;
            }
            delete query.maxId;
        } else if (type === 'next') {
            const list = contentObj ? contentObj.list : [];
            query.maxId = list[list.length - 1].id;
            delete query.minId;
        }

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '到付件管理',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    // 选择显示行数
    onShowSizeChange = (psize: number) => {
        const { formValues } = this.state;
        const query = { ...formValues, page: 1, psize };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '到付件管理',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    // 渲染查询表单
    renderSearchFormElem = () => {
        const {
            form: { getFieldDecorator },
            INITINFO: { expressList, logisList },
        } = this.props;
        const chargeStatus = { 0: '未付款', 1: '已付款' };

        return (
            <Form onSubmit={this.handleSearch} className="tableListForm">
                <Row gutter={12}>
                    <Col md={12} sm={24}>
                        <Item label="起止时间" colon={false}>
                            {getFieldDecorator('start_end_time', {
                                initialValue: [
                                    moment(
                                        moment()
                                            .subtract(3, 'days')
                                            .format('YYYY-MM-DD 00:00:00'),
                                    ),
                                    '',
                                ],
                            })(
                                <RangePicker
                                    showTime
                                    placeholder={['开始时间', '截止时间']}
                                    style={{ width: '100%' }}
                                    format="YYYY/MM/DD HH:mm:ss"
                                    disabledDate={timeLimit}
                                    ranges={{
                                        今天: [moment().startOf('day'), moment().endOf('day')],
                                        本周: [moment().startOf('week'), moment().endOf('week')],
                                        本月: [moment().startOf('month'), moment().endOf('month')],
                                        上月: [
                                            moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                                            moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                                        ],
                                    }}
                                />,
                            )}
                        </Item>
                    </Col>
                    <Col md={6} sm={24}>
                        <Item label="　付款状态" colon={false}>
                            {getFieldDecorator('chargeStatus')(
                                <Select allowClear placeholder="请选择">
                                    {Object.keys(chargeStatus).map(key => (
                                        <Option key={String(key)} value={String(key)}>
                                            {chargeStatus[key]}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </Item>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col md={6} sm={24}>
                        <Item label="物流中心" colon={false}>
                            {getFieldDecorator('logisId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {logisList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </Item>
                    </Col>
                    <Col md={6} sm={24}>
                        <Item label="　　运单号" colon={false}>
                            {getFieldDecorator('expCode')(
                                <Input allowClear placeholder="请输入" />,
                            )}
                        </Item>
                    </Col>
                    <Col md={6} sm={24}>
                        <Item label="　订单状态" colon={false}>
                            {getFieldDecorator('orderStatus')(
                                <Select allowClear placeholder="请选择">
                                    {Object.keys(orderStatus).map(key => (
                                        <Option key={String(key)} value={String(key)}>
                                            {orderStatus[key]}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </Item>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col md={6} sm={24}>
                        <Item label="快递公司" colon={false}>
                            {getFieldDecorator('expressId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {expressList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </Item>
                    </Col>
                    <Col md={6} sm={24}>
                        <Item label="收件人手机" colon={false}>
                            {getFieldDecorator('consigneePhone')(
                                <Input allowClear placeholder="请输入" />,
                            )}
                        </Item>
                    </Col>
                    <Col md={6} sm={24}>
                        <div className="flexFeView">
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="smallButton"
                            >
                                查询
                            </Button>
                            <Button
                                type="primary"
                                className="addButton smallButton marginL16"
                                onClick={this.handleReset}
                            >
                                重置
                            </Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        );
    };

    render() {
        const { current, pageSize } = this.state;
        const {
            logisCenterPayexpList: { data },
            loading,
            screen,
        } = this.props;

        const contentObj = data.content.find((item: any) => item.current === current);
        const list = contentObj ? contentObj.list : [];

        if (screen === 'sm' || screen === 'lg') {
            delete this.columns[this.columns.length - 1].fixed;
        } else if (screen === 'md') {
            this.columns[this.columns.length - 1].fixed = 'right';
        }

        return (
            <>
                <PageHeader />

                <Card bordered={false} className="searchForm">
                    {this.renderSearchFormElem()}
                </Card>

                <Card bordered={false} className="tableList">
                    <div className="tableBtns">
                        <Button
                            type="primary"
                            size="small"
                            className="smallButton"
                            onClick={this.handleExport}
                        >
                            导出Excel
                        </Button>
                    </div>
                    <Table
                        rowKey="id"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={list}
                        pagination={false}
                        loading={loading}
                        scroll={{ x: 1600 }}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />
                    {(current > 1 || list.length > 0) && (
                        <Pagination
                            current={current}
                            pageSize={pageSize}
                            total={data.count}
                            length={list.length}
                            showCount={this.handleShowCount}
                            onChange={this.onSelectChange}
                            onShowSizeChange={this.onShowSizeChange}
                        />
                    )}
                </Card>

            </>
        );
    }
}

export default Form.create<TableListProps>()(TableList);
